# Create your views here.
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse,HttpResponseRedirect

from models import *
import datetime

def new(request):    
    if request.method == 'POST':
        Post(title=request.POST['title'],
             author=request.POST['author'],
             content=request.POST['content'],
             date=datetime.datetime.now()).save()
        return HttpResponseRedirect('/codingdojo/blog/')

    return render_to_response('blog/new.html',
                              context_instance=RequestContext(request))

def index(request):   
    message = None
    if 'message' in request.session:
        message = request.session['message']
        del request.session['message']
    posts = Post.objects.all().order_by('-date')
    return render_to_response('blog/index.html',
                              {'posts': posts,
                               'message' : message},
                              context_instance=RequestContext(request))

def remove(request, id):
    try:
        Post.objects.get(id=id).delete()
        request.session['message'] = 'Post removido com sucesso'
    except Post.DoesNotExist:
        pass
    return HttpResponseRedirect('/codingdojo/blog/')

def rss(request):
    return HttpResponse('rss')

def post(request, id):
    post = Post.objects.get(id=id)
    return render_to_response('blog/post.html',
                              {'post' : post},
                              context_instance=RequestContext(request))      
    
def comment_new(request, post_id):
    post = Post.objects.get(id=post_id)
    c = Comment(post=post, author=request.POST['author'] , 
                date=datetime.datetime.now(), 
                content=request.POST['content'])
    post.comment_set.add(c)
    return HttpResponse()                        